package com.itheima.thread03;

public class MyThread03 implements Runnable{

    private static int tickets = 100;
    @Override
    public void run() {
        while (true) {
//            if ("窗口一".equals(Thread.currentThread().getName())) {
//                boolean result = synchronizedmethod();
//                if (result){
//                    break;
//                }
//            }
            if ("窗口一".equals(Thread.currentThread().getName())) {
                boolean result = synchronizedmethod1();
                if (result){
                    break;
                }
            }
            if ("窗口二".equals(Thread.currentThread().getName())) {
                synchronized (MyThread03.class) {
                    if (tickets <= 0) {
                        System.out.println("已售罄");
                        break;
                    } else {
                        try {
                            //线程会在这里休眠100毫秒，因为实际买票是需要时间的
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        //卖完一张就减一张
                        tickets--;
                        //然后打印出剩余票数
                        System.out.println(Thread.currentThread().getName() + "在卖票，还剩" + tickets + "张票");
                    }
                }
            }
        }
    }

    private static synchronized boolean synchronizedmethod1() {
        if (tickets <= 0) {
            System.out.println("已售罄");
            return true;
        } else {
            try {
                //线程会在这里休眠100毫秒，因为实际买票是需要时间的
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //卖完一张就减一张
            tickets--;
            //然后打印出剩余票数
            System.out.println(Thread.currentThread().getName() + "在卖票，还剩" + tickets + "张票");
            return false;
        }
    }

    private synchronized boolean synchronizedmethod() {
        if (tickets <= 0) {
            System.out.println("已售罄");
            return true;
        } else {
            try {
                //线程会在这里休眠100毫秒，因为实际买票是需要时间的
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //卖完一张就减一张
            tickets--;
            //然后打印出剩余票数
            System.out.println(Thread.currentThread().getName() + "在卖票，还剩" + tickets + "张票");
            return false;
        }
    }
}
